#! /usr/bin/env python3
import sys
import os
import urllib.parse as parse

class FindMessage(object):
	def __init__(self, file_name, key_words):
		self.file_name = file_name
		self.key_words = key_words.lower()

	def do(self):
		key_list = self.key_words.split(' ')
		lab = list()
		final = dict()
		for key in key_list:
			get_list = self.find_key_word(key)
			if get_list == []:
				lab.append(False)
			else:
				final.setdefault(key, get_list)
				lab.append(True)
		if False in lab:
			return None
		else:
			return final

	def get_content(self):
		content = ""
		try:
			with open(self.file_name, 'r', encoding='UTF-8') as f:
				content = f.read()
		except Exception:
			pass
		if not content:
			return ""
		return content.lower()

	def find_key_word(self,key_word):
		content = self.get_content()
		find_count = content.count(key_word)
		if find_count == 0:
			return list()
		find_list = list()
		for r in range(find_count):
			content = content
			find_key = content.find(key_word)
			start_key =find_key - 10
			end_key = find_key + 10
			if find_key - 10 < 0:
				start_key = 0
			else:
				start_key = find_key - 10
			if end_key > len(content):
				end_key = len(content)
			else:
				end_key = find_key + 10
			result = content[start_key : end_key].replace('\n',' ')
			find_list.append(result)
			content = content[end_key:]
		return find_list


def create_div(in_FindMessage, execs, file_path):
	find_list = in_FindMessage.do()
	title_raw = in_FindMessage.file_name
	title = title_raw.replace("\\", "/").split('/')[-1]
	keywords = ''
	final_list = list()
	if find_list == None:
		return ''
	for key in find_list:
		keywords += key + ' '
		find_cont = '...'.join(find_list[key])

		c = 100
		if len(find_cont) > c:
			c_len = len(find_cont)
			temp_c_list = list()
			for i in range(int((c_len / c)) + 1):
				maxs = (c * (i + 1))
				if (c * (i + 1)) > c_len:
					maxs = c_len
				temp = find_cont[(c * i): maxs]
				temp_c_list.append(temp)
			find_cont = '<br />'.join(temp_c_list)
		find_cont = find_cont.replace(key, '<b>' + key + '</b>')
		
		final_list.append(find_cont)
	text = '\n'.join(final_list)
	text = text.replace('<div', '&lt;div')
	text = text.replace('</div', '&lt;/div')
	final_text = '<div class="resul">\n<span><a href="' + execs + '?file=' +\
	 parse.quote(title_raw.replace(file_path, "")) + '" target="view_window">' +\
	 title + '</a></span></br><hr></br>\n<b class="keywords">关键词</b>     <span class = "t">' + keywords +\
	  '</span></br></br>\n<p class="con">' + text +'</p>\n</div>\n'
	return final_text



def main(file_path, keywords, execs, head_path):
	word = FindMessage(file_path, keywords)
	res = create_div(word, execs, head_path)
	return res


if __name__ == "__main__":
	print(main(r"D:\笔记备份\notes\程序笔记\c++\C++基础\常用宏定义.md", "#", ""))